$(function () {
     // 定义状态变量
    let isUsernameReady = false,
        isPasswordReady = false,
        isemailReady=false;
    //鼠标离开事件
    let $username=$('input[name="username"]');
    $username.blur(fnCheckUsername)
    //检测用户名
    function fnCheckUsername(){
        let sUsername=$username.val();
        if (sUsername===''){
             message.showError('用户名不能为空')
            return
        }
        if (!(/^\w{5,20}$/).test(sUsername)){
             message.showError('请输入5-20个字符的用户名')
        }
        $.ajax(
            {
                url:'/user/username/'+sUsername+'/',
                type:'GET',
                dataType:'json',
                success:function (data) {
                    if (data.data.count > 0){
                        message.showError(data.data.username+'已经注册，请重新输入！')
                    }else {
                        message.showInfo(data.data.username + '可以正常使用！');
                        isUsernameReady = true
                    }

                },
                error: function (xhr, msg) {
                 message.showError('服务器超时，请重试！')
            }
            }
        )
    }
    // 检测密码是否一致
    let $passwordRepeat=$('input[name="password_repeat"]');
    $passwordRepeat.blur(fnCheckPassword);
    function fnCheckPassword() {
         isPasswordReady = false;
         let password = $('input[name="password"]').val();
         let passwordRepeat = $passwordRepeat.val();
         if(password ===''||passwordRepeat ===''){
               message.showError('密码不能为空')
              return
         }
         if(password != passwordRepeat){
             message.showError('两次密码输入不正确')
             return
         }
         if (password === passwordRepeat) {
            message.showInfo('两次密码输入正确')
            isPasswordReady = true
        }
     }
     //检测邮箱
    let $email=$('input[name="email"]');
    $email.blur(fnCheckemail)
    function fnCheckemail() {
        let sEmail=$email.val();
        if (sEmail===''){
            message.showError('邮箱不能为空')
            return
        };
        if(!(/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/).test(sEmail)){
            message.showError('邮箱格式输入错误')
            return
        }else {
            message.showInfo('邮箱输入正确')
        };
        $.ajax(
            {
                url:'/user/email/'+sEmail+'/',
                type:'GET',
                dataType:'json',
                success:function (data) {
                    if (data.data.count > 0){
                        message.showError(data.data.username+'此邮箱已经存在，请重新输入！')
                    }else {
                        message.showInfo(data.data.username + '邮箱可以正常使用！');
                        isemailReady = true
                    }

                },
                error: function (xhr, msg) {
                 message.showError('服务器超时，请重试！')
            }
            }
        )

    }
    //点击事件
    //注册
    let $submitBtn = $('.signin_btn_two');
    $submitBtn.click(function (e) {
        //阻止默认提交
        e.preventDefault();
        //检查用户名
        if(!isUsernameReady){
            fnCheckUsername();
            return
        }
        //检查密码
        if(!isPasswordReady){
            fnCheckPassword();
            return;
        }
        //检查邮箱
        if(!isemailReady){
            fnCheckemail();
            return;
        }
        $.ajax(
            {
                url:'/user/registe/',
                type:"POST",
                data:{
                    username: $username.val(),
                    password: $('input[name="password"]').val(),
                    password_repeat: $passwordRepeat.val(),
                    email: $email.val(),
                },
                dataType: 'json',
                success: function (res) {
                if(res.errno === '0'){
                    message.showSuccess('恭喜您，注册成功!');
                    setTimeout(function () {
                        //注册成功后重定向到登录页面
                        window.location.href = '/user/login/'
                    }, 3000)
                }else{
                    //注册失败
                    message.showError(res.errmsg)
                }
            },
            error: function () {
                message.showError('服务器超时，请重试！')
            }


        }
        )

    })
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        }
    });
});
